package com.hrbxlh.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.ChapterActionImpl;
import com.hrbxlh.actionImpl.ClassActionImpl;
import com.hrbxlh.actionImpl.CourseActionImpl;
import com.hrbxlh.actionImpl.HomeworkTestActionImpl;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.FileUpload;
import com.hrbxlh.util.SessionValues;

/**
* -------------------------------------------------------
* Copyright (c) 2017, 鑫联华信息科技股份有限公司
* All rights reserved.
* FileName：HomeworkTestAction.java
* Description：作业和试验action类
* History：
* Date           Author               Desc
* 2017.4.5		  xzx                 建立
* -------------------------------------------------------
*/

@Controller
public class HomeworkTestAction {

	@Autowired
	@Qualifier("homeworkTestActionImpl")
	private HomeworkTestActionImpl homeworkTestActionImpl;
	
	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;
	
	@Autowired
	@Qualifier("chapterActionImpl")
	private ChapterActionImpl chapterActionImpl;
	
	@Autowired
	@Qualifier("classActionImpl")
	private ClassActionImpl classActionImpl;
	
	/**作业管理  进页面
	 * @description 进页面，带登录人教的课程信息（id，名字） 带教师教的班级信息（班级id，班级名称）
		列表：课程名，作业名称，上课时间，交作业进度，（交作业人数，全部人数），查看按钮      带分页
	 * @param request
	 * @param response
	 * //Map<String, Object> mapUse=new HashMap<String, Object>();
		//mapUse.put("pageNow", 1);
		//mapUse.put("pageSize", 10);
		//mapUse.put("courseId", 19);
		//jsonStr = mapper.writeValueAsString(mapUse);
	 * @return  跳转到作业管理页面（导航） 以及条件查询
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipHomeworkMana", method = RequestMethod.GET)
	public ModelAndView skipHomeworkMana(String jsonStr,HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try {
			Map<String,Object> preParamMap = new HashMap<String, Object>();
			//获取参数值
			if(jsonStr != null){
				preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			}
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request);
			preParamMap.put("stuorteaId", sessionValues.get("stuorteaId"));
			//获取教师教的课程id以及名称
			List<Map<String, Object>> courseList = courseActionImpl.getTeaTeachCourse(preParamMap);
			resultMap.put("courseList", courseList);
			//获取教师的所有班级（从中间表里查）
			List<Map<String, Object>> classList = homeworkTestActionImpl.getTeaTeachClass(preParamMap);
			resultMap.put("classList", classList);
			//获取课堂班级课程作业情况
			Map<String, Object> homeworkListMap = homeworkTestActionImpl.getTeaHomeworkList(preParamMap);
			if(homeworkListMap != null){
				resultMap.put("homeworkList", homeworkListMap.get("homeworkList"));
				resultMap.put("totalPage", homeworkListMap.get("totalPage"));
				resultMap.put("pageNow", homeworkListMap.get("pageNow"));
			}
			//返回条件
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			if(preParamMap.get("courseId") != null){
				resultMap.put("courseId", preParamMap.get("courseId"));
			}
			if(preParamMap.get("classId") != null){
				resultMap.put("classId", preParamMap.get("classId"));
			}
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//作业管理列表页面
			pageName = "pc/homeworkMana";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转作业管理页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**实验管理  进页面
	 * @description 进页面，带登录人教的课程信息（id，名字） 带教师教的班级信息（班级id，班级名称）
		列表：课程名，作业名称，上课时间，交实验进度，（交作业人数，全部人数），查看按钮      带分页
	 * @param request
	 * @param response
	 * //Map<String, Object> mapUse=new HashMap<String, Object>();
		//mapUse.put("pageNow", 1);
		//mapUse.put("pageSize", 10);
		//mapUse.put("courseId", 19);
		//jsonStr = mapper.writeValueAsString(mapUse);
	 * @return  跳转到实验管理页面（导航） 以及条件查询
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipTestMana", method = RequestMethod.GET)
	public ModelAndView skipTestMana(String jsonStr,HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try {
			Map<String,Object> preParamMap = new HashMap<String, Object>();
			//获取参数值
			if(jsonStr != null){
				preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			}
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId"}, request);
			preParamMap.put("stuorteaId", sessionValues.get("stuorteaId"));
			//获取教师教的课程id以及名称
			List<Map<String, Object>> courseList = courseActionImpl.getTeaTeachCourse(preParamMap);
			resultMap.put("courseList", courseList);
			//获取教师的所有班级（从中间表里查）
			List<Map<String, Object>> classList = homeworkTestActionImpl.getTeaTeachClass(preParamMap);
			resultMap.put("classList", classList);
			//获取课堂班级课程实验情况
			Map<String, Object> testListMap = homeworkTestActionImpl.getTeaTestList(preParamMap);
			if(testListMap != null){
				resultMap.put("testList", testListMap.get("testList"));
				resultMap.put("totalPage", testListMap.get("totalPage"));
				resultMap.put("pageNow", testListMap.get("pageNow"));
			}
			//返回条件
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			if(preParamMap.get("courseId") != null){
				resultMap.put("courseId", preParamMap.get("courseId"));
			}
			if(preParamMap.get("classId") != null){
				resultMap.put("classId", preParamMap.get("classId"));
			}
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//作业管理列表页面
			pageName = "pc/testMana";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转实验管理页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**作业管理  作业提交详情页面
	 * @description 作业提交详情页面,展示学生信息作业信息 不分页
	 * @param request
	 * @param response
	 * 		//Map<String, Object> mapUse=new HashMap<String, Object>();
			//mapUse.put("courseId", 18);
			//mapUse.put("chapterId", 21);
			//mapUse.put("classId", 4);
			//jsonStr = mapper.writeValueAsString(mapUse);
	 * @return 
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipHomeworkDetail", method = RequestMethod.GET)
	public ModelAndView skipHomeworkDetail(String jsonStr,HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try {
			Map<String,Object> preParamMap = new HashMap<String, Object>();
			//获取参数值
			if(jsonStr != null){
				preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			}
			//班级名称
			Map<String ,Object> classMap = classActionImpl.getClassNameById(preParamMap);
			resultMap.put("classMsg", classMap);
			//章节名称
			Map<String, Object> chapterMap = chapterActionImpl.getCourseOneChapter(preParamMap);
			resultMap.put("chapterMsg", chapterMap);
			//列表信息
			Map<String, Object> homeworkListMap = homeworkTestActionImpl.getHomeWorkByClass(preParamMap);
			if(homeworkListMap != null){
				resultMap.put("homeworkList", homeworkListMap.get("homeworkList"));
				resultMap.put("totalPage", homeworkListMap.get("totalPage"));
				resultMap.put("pageNow", homeworkListMap.get("pageNow"));
			}
			//返回条件
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			//获取图片前缀   http://localhost:8081/SchoolManageSystem/images/pc/+文件名
			String[] keysArray = {"server_address", "project_name"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String imageUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"images/pc/";
			resultMap.put("imageUrl", imageUrl);
			//获取作业文件前缀
			String homeworkUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/course/";
			resultMap.put("homeworkUrl", homeworkUrl);
			//返回条件
			resultMap.put("courseId", preParamMap.get("courseId"));
			resultMap.put("chapterId", preParamMap.get("chapterId"));
			resultMap.put("classId", preParamMap.get("classId"));
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//班级作业详情列表页面
			pageName = "pc/homeworkList";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转作业管理内页页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**实验管理 实验提交详情页面
	 * @description 实验提交详情页面,展示学生信息实验信息  不分页
	 * @param request
	 * @param response
	 * 	//Map<String, Object> mapUse=new HashMap<String, Object>();
		//mapUse.put("courseId", 18);
		//mapUse.put("chapterId", 21);
		//mapUse.put("classId", 4);
		//jsonStr = mapper.writeValueAsString(mapUse);
	 * @return 
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/skipTestDetail", method = RequestMethod.GET)
	public ModelAndView skipTestDetail(String jsonStr,HttpServletRequest request, HttpServletResponse response) throws IOException {		
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//存放页面
		String pageName = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try {
			Map<String,Object> preParamMap = new HashMap<String, Object>();
			//获取参数值
			if(jsonStr != null){
				preParamMap = mapper.readValue(jsonStr, resultMap.getClass());
			}
			//班级名称
			Map<String ,Object> classMap = classActionImpl.getClassNameById(preParamMap);
			resultMap.put("classMsg", classMap);
			//章节名称
			Map<String, Object> chapterMap = chapterActionImpl.getCourseOneChapter(preParamMap);
			resultMap.put("chapterMsg", chapterMap);
			//列表信息
			Map<String, Object> testListMap = homeworkTestActionImpl.getTestByClass(preParamMap);
			if(testListMap != null){
				resultMap.put("testList", testListMap.get("testList"));
				resultMap.put("totalPage", testListMap.get("totalPage"));
				resultMap.put("pageNow", testListMap.get("pageNow"));
			}
			//返回条件
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			//获取图片前缀   http://localhost:8081/SchoolManageSystem/images/pc/+文件名
			String[] keysArray = {"server_address", "project_name"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String imageUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"images/pc/";
			resultMap.put("imageUrl", imageUrl);
			//获取实验文件前缀
			String testUrl = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/course/";
			resultMap.put("testUrl", testUrl);
			//返回条件
			resultMap.put("courseId", preParamMap.get("courseId"));
			resultMap.put("chapterId", preParamMap.get("chapterId"));
			resultMap.put("classId", preParamMap.get("classId"));
			//获取我的消息
			List<Map<String, Object>> noticeList  = courseActionImpl.getMyNotice(request);
			resultMap.put("noticeList", noticeList);
			//班级作业详情列表页面
			pageName = "pc/testList";
		} catch (Exception e) {
			resultMap.put("errMsg", "跳转页面失败");
			e.printStackTrace();
			logger.error("跳转实验管理内页页面出现异常", e);
			pageName = "public/pageerror";
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			returnMap.put("result", reJsonStr);
			System.out.println("返回的  :" + reJsonStr);
		}
		return new ModelAndView(pageName, returnMap);
	}
	
	/**作业管理评价学生作业
	 * @description 评价学生作业
	 * @param request
	 * @param response
	 * 	//Map<String, Object> map = new HashMap<String ,Object>();
		//map.put("courseId", 18);
		//map.put("chapterId", 21);
		//map.put("stuorteaId", 5);
		//map.put("taskFraction", "优");
		//map.put("submitContent", "好好学习啊啊啊啊啊");
		//jsonStr = mapper.writeValueAsString(map);
	 * @param 需要   课程id，章节id，学生号
	 * @return  课表信息
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/assessHomework", method = RequestMethod.POST)
	public void  assessHomework (HttpServletResponse response, HttpServletRequest request, String jsonStr,HttpSession session) throws IOException {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//添加评价
			Map<String,Object> assessMark = homeworkTestActionImpl.assessHomework(paramMap,request);
			String resultMark = ((Boolean)assessMark.get("result")) ? "success" : "fail";
			//添加该学生本门课程平时成绩
			if(resultMark.equals("success")){
				//添加该学生本门课程平时成绩
				homeworkTestActionImpl.addNormalNum(paramMap);
				homeworkTestActionImpl.reCountDegree(paramMap,session);
				//返回标识
				resultMap.put("result", resultMark);
			}else{
				//返回标识
				resultMap.put("result", "fail");
				resultMap.put("failMsg", assessMark.get("failMsg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("评价作业出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
	/**实验管理评价学生实验
	 * @description 评价学生实验
	 * @param request
	 * @param response
	 * 	//Map<String, Object> map = new HashMap<String ,Object>();
		//map.put("courseId", 18);
		//map.put("chapterId", 21);
		//map.put("stuorteaId", 5);
		//map.put("taskFraction", "优");
		//map.put("submitContent", "好好学习啊啊啊啊啊");
		//jsonStr = mapper.writeValueAsString(map);
	 * @param 需要   课程id，章节id，学生号
	 * @return  课表信息
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/assessTest", method = RequestMethod.POST)
	public void  assessTest (HttpServletResponse response, HttpServletRequest request, String jsonStr,HttpSession session) throws IOException {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try { 
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//添加评价
			Map<String, Object> assessMark = homeworkTestActionImpl.assessTest(paramMap,request);
			String resultMark = ((Boolean)assessMark.get("result")) ? "success" : "fail";
			if(resultMark.equals("success")){
				//添加该学生本门课程平时成绩
				homeworkTestActionImpl.addNormalNum(paramMap);
				homeworkTestActionImpl.reCountDegree(paramMap,session);
				//返回标识
				resultMap.put("result", resultMark);
			}else{
				//返回标识
				resultMap.put("result", resultMark);
				resultMap.put("failMsg", assessMark.get("failMsg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("评价实验出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
	/***作业管理
	 * @description 提交作业
	 *  需要课程id，章节id（主键），类型（作业还是实验）
	 * @param response
	 * @param request
	 * @param chapterId
	 * @param courseId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/stuUploadHomework", method = RequestMethod.POST)
	public String  stuUploadHomework  (HttpServletRequest request,
			long courseId,
			long chapterId,
			long taskType,
			@RequestParam("file") CommonsMultipartFile file
			) throws IOException {
		
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		try { 
			FileUpload fileUpload = new FileUpload();
			//上传作业(20170622商莹修改了下载文件方法的返回类型)
			Map<String,Object> uploadMapThree =  fileUpload.fileUploadParam(file, request);
			String fileName = (String) uploadMapThree.get("result");
			resultMap.put("courseId", courseId);
			resultMap.put("chapterId", chapterId);
			resultMap.put("taskType", taskType);
			resultMap.put("taskAddress", fileName);
			//获取登录人id
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"stuorteaId","roleId"}, request);
			resultMap.put("stuorteaId", sessionValues.get("stuorteaId"));
			//添加作业信息
			boolean addResult = homeworkTestActionImpl.addTask(resultMap);
			if(addResult){
				String json = "%7B%22courseId%22:"+courseId+",%22pageMark%22:1"+"%7D";
				reJsonStr = "redirect:/skipCourseStudyDetail?jsonStr="+json;
			}else{
				reJsonStr="redirect:/skipErrorPage";
			}	
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("上传作业出现异常", e);
		} finally {}
		return reJsonStr;
	}
	
	/**实验管理   学生提交试验报告
	 * @description  
	 * @param request
	 * @param response
	 * 
	 * @param 需要   课程id，章节id，学生号
	 * @return  课表信息
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/uploadTest", method = RequestMethod.POST)
	public void  uploadTest (HttpServletResponse response, HttpServletRequest request, String jsonStr) throws IOException {
		
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(HomeworkTestAction.class.getName());
		try { 
//			Map<String, Object> map = new HashMap<String ,Object>();
//			map.put("courseId", 1);
//			map.put("chapterId", 1);
//			map.put("stuorteaId", 1206);
//			map.put("taskType", 2);
//			map.put("taskAddress", "好好学习啊啊啊啊啊试验内容啊啊啊");
//			jsonStr = mapper.writeValueAsString(map);
			
			
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//添加试验信息
			boolean addResult = homeworkTestActionImpl.addTask(paramMap);
			String resultMark = (addResult) ? "success" : "fail";
			resultMap.put("result", resultMark);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("提交试验出现异常", e);
		} finally {
			reJsonStr = mapper.writeValueAsString(resultMap);
			System.out.println("返回的："+reJsonStr);
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter write = response.getWriter();
			write.println(reJsonStr);
			write.flush();
		}
	}
	
}